<template>
  <div class="project-management-container">
    <!-- 筛选条件区域 -->
    <div class="filter-container">
      <el-form :model="filterParams" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="项目名称">
              <el-input
                v-model="filterParams.projectName"
                placeholder="请输入项目名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目产业类别">
              <el-select
                v-model="filterParams.industryCategory"
                placeholder="请选择产业类别"
                clearable
              >
                <el-option
                  v-for="item in industryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="投资方">
              <el-input
                v-model="filterParams.investor"
                placeholder="请输入投资方"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleExport" :title="selectedProjects.length > 0 ? '导出选中项目' : '导出全部项目'">
       <el-icon><Download /></el-icon>
       导出Excel
       <span v-if="selectedProjects.length > 0">({{ selectedProjects.length }}项)</span>
      </el-button>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增项目
      </el-button>
    </div>

    <!-- 项目表格区域 -->
    <div class="table-container">
       <!-- 标题和分割线 -->
      <div class="header-section">
        <h1 class="contract-title">在谈项目</h1>
        <div class="divider"></div>
      </div>
      <el-table
        :data="paginatedProjects"
        border
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="项目名称" width="200">
         <template #default="{ row }">
          <router-link 
           :to="{
             name: 'InTalkProjectDetail',
             params: { id: row.id },
             query: { projectData: JSON.stringify(row) }
            }"
           class="project-link"
          >
          {{ row.projectName }}
         </router-link>
         </template>
        </el-table-column>
        <el-table-column prop="projectCode" label="项目编号" />
        <el-table-column prop="investor" label="投资方" width="150" />
        <el-table-column prop="contactPerson" label="联系人" width="120" />
        <el-table-column prop="industryCategory" label="项目产业类别" width="150">
          <template #default="{ row }">
            <el-tag :type="getIndustryTagType(row.industryCategory)">
              {{ row.industryCategory }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="parkName" label="所属园区" width="150" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
            type="success"
            size="small"
            @click="handleChangeStatus(row)"
            >
            标记签约
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑项目对话框 -->
    <ProjectDialog
      v-model="dialogVisible"
      :dialog-type="dialogType"
      :current-project="currentProject"
      @refresh="fetchProjectList"
    />
  </div>
</template>

<script setup>
import { ref, onMounted,computed } from 'vue'
import { Download, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'
import ProjectDialog from './component/ProjectDialog.vue'


import axios from 'axios'

// API基础URL（从环境变量获取，自动适配环境）
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

const projects = ref([])

// 筛选参数
const filterParams = ref({
  projectName: '',
  industryCategory: '',
  investor: ''
})

// 产业类别选项
const industryOptions = ref([
  { value: '制造业', label: '制造业' },
  { value: '信息技术', label: '信息技术' },
  { value: '金融业', label: '金融业' },
  { value: '教育培训', label: '教育培训' },
  { value: '医疗健康', label: '医疗健康' },
  { value: '零售业', label: '零售业' },
  { value: '物流运输', label: '物流运输' },
  { value: '建筑工程', label: '建筑工程' },
  { value: '餐饮服务', label: '餐饮服务' },
  { value: '文化娱乐', label: '文化娱乐' },
  { value: '房地产', label: '房地产' },
  { value: '能源环保', label: '能源环保' },
  { value: '农业', label: '农业' },
  { value: '旅游酒店', label: '旅游酒店' },
  { value: '媒体广告', label: '媒体广告' },
  { value: '咨询服务', label: '咨询服务' },
  { value: '其他行业', label: '其他行业' }
])

// 使用计算属性获取过滤后的项目列表
const filteredProjects = computed(() => {
  return projects.value.filter(item => item.state === 'inTalk')
})

// 获取项目列表的方法
const fetchProjectList = async () => {
  loading.value = true
try {
    console.log('发送请求，参数:', filterParams.value)
    const response = await axios.get(`${API_BASE_URL}/api/projects`, {
      params: filterParams.value
    })
    console.log('收到响应:', response.data)
    projects.value = response.data
    console.log('项目数据已更新，数量:', projects.value.length)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
    }
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 分页后的项目列表
const paginatedProjects = computed(() => {
  const filtered = filteredProjects.value
    const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
    const end = start + pagination.value.pageSize
    console.log('分页数据:', {
      total: filtered.length,
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      start,
      end,
      data: filtered.slice(start, end)
    })
    return filtered.slice(start, end)
})

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: computed(() => filteredProjects.value.length)
})
// 加载状态
const loading = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' or 'edit'
const currentProject = ref({})



// 查询项目
const handleQuery = () => {
  pagination.value.currentPage = 1
  fetchProjectList() // 需要添加这行
}

// 重置筛选条件
const handleReset = () => {
  filterParams.value = {
    projectName: '',
    industryCategory: '',
    investor: ''
  }
  handleQuery()
  
}

// 添加选中项目的ref
const selectedProjects = ref([])

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedProjects.value = selection
}

// 导出Excel方法
const handleExport = () => {
  // 如果有选中项目，则导出选中项目，否则导出全部
  const exportData = selectedProjects.value.length > 0 
    ? selectedProjects.value 
    : filteredProjects.value
  
  if (exportData.length === 0) {
    ElMessage.warning('没有可导出的项目数据')
    return
  }

  const worksheet = XLSX.utils.json_to_sheet(exportData)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '项目信息')
  
  const fileName = selectedProjects.value.length > 0
    ? `选中项目_${new Date().toLocaleDateString()}.xlsx`
    : `全部项目_${new Date().toLocaleDateString()}.xlsx`
  
  XLSX.writeFile(workbook, fileName)
}

// 新增项目
const handleAdd = () => {
  dialogType.value = 'add'
  currentProject.value = {}
  dialogVisible.value = true
}

// 修复后的 handleChangeStatus 方法
const handleChangeStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要将项目 "${row.projectName}" 标记为已签约吗？`,
      '确认签约',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 设置加载状态
    row.signing = true
    
    // 使用统一的api实例，修复路径问题
    await axios.post(`${API_BASE_URL}/api/projects/${row.id}/sign`)
    
    ElMessage.success('项目已标记签约')
    
    // 重新获取数据，更新列表
    await fetchProjectList()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态更新失败:', error)
      
      // 完善错误处理
      if (error.response) {
        const errorMsg = error.response.data?.message || error.response.data || '签约失败'
        ElMessage.error(`标记签约失败: ${errorMsg}`)
      } else if (error.request) {
        ElMessage.error('网络错误，请检查服务器连接')
      } else {
        ElMessage.error('签约失败，请重试')
      }
    }
  } finally {
    // 确保无论成功失败都清除加载状态
    row.signing = false
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
}

// 获取产业类别标签类型
const getIndustryTagType = (category) => {
  const map = {
    '智能制造': '',
    '电子信息': 'success',
    '生物医药': 'warning',
    '新能源': 'danger',
    '新材料': 'info'
  }
  return map[category] || ''
}

onMounted(() => {
  fetchProjectList() // 组件加载时获取数据
})
</script>

<style scoped>
.project-management-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
}

.operation-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.filter-container {
  margin-bottom: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.header-section {
  margin-bottom: 30px;
}

.contract-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
  text-align: left;
}

.divider {
  height: 1px;
  background-color: #e0e0e0;
  width: 100%;
}

</style>